package comnet

import (
	"TODecider/src/logger"
	"TODecider/src/pb"
	"errors"
)

var (
	comNet      NetV3
	log         = logger.GetLogger()
	NodeIPMap   = make(map[string]Node)
	nodeEncoder = make(map[string]int)
	nodeDecoder = make(map[int]string)
)

func Encode(s string) int {
	return nodeEncoder[s]
}

func Decode(i int) string {
	return nodeDecoder[i]
}

func PullRecentComNet() (NetV3, error) {
	if len(comNet.Nodes) == 0 {
		err := errors.New("[ComNet] no ComNet in the queue")
		return comNet, err
	} else {
		log.Debugf("[ComNet] pull ComNet: %v", comNet)
		for i, node := range comNet.Nodes {
			nodeEncoder[node.Ip] = i
			nodeDecoder[i] = node.Ip
			NodeIPMap[node.Ip] = node
		}
		return comNet, nil
	}
}

func StoreComNet(comNetIn *pb.ComNet) {
	if comNetIn != nil {
		comNet = fromPbComNet(comNetIn)
		log.Debugf("[ComNet] store ComNet: %v", comNet)
	}
}
